package com.hao.wms.dao.impl;

import com.hao.wms.VO.OrderChartVO;
import com.hao.wms.VO.OrderGroupByType;
import com.hao.wms.dao.IOrderChartDao;
import com.hao.wms.query.OrderChartQueryObject;
import com.hao.wms.query.QueryObject;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.util.List;

public class OrderChartDaoImpl implements IOrderChartDao {
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public List<OrderChartVO> queryOrderChart(OrderChartQueryObject queryObject) {
        OrderGroupByType groupByType = OrderGroupByType.valueOf(queryObject.getGroupTpye());
        Session session = sessionFactory.getCurrentSession();
        StringBuilder hql = new StringBuilder(80);
        hql.append("SELECT NEW OrderChartVO(").append(groupByType.getGroupValue()).append(",SUM(obj.number),SUM(obj.amount)) FROM OrderBillItem obj");
        hql.append(queryObject.getQuery());
        hql.append(" GROUP BY ").append(groupByType.getGroupBy());
        Query query = session.createQuery(hql.toString());
        setParams(queryObject, query);
        return query.list();
    }

    private void setParams(QueryObject qo, Query query) {
        for (int i = 0; i < qo.getParams().size(); i++) {
            query.setParameter(i, qo.getParams().get(i));
        }
    }
}
